import React, { useRef, useEffect } from 'react'
import * as THREE from 'three';
import Stats from 'three/addons/libs/stats.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';

// import modal from '@/assets/modals/'

const ThreeComponent = ()=>{
    const wraperRef = useRef();

    useEffect(()=>{
        let mixer;
        const clock = new THREE.Clock();
        
        const camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 1000 );
        camera.position.set( 5, 2, 8 );
        const container = wraperRef.current;

        const renderer = new THREE.WebGLRenderer({ antialias: true });

        const pmremGenerator = new THREE.PMREMGenerator( renderer );

        const stats = new Stats();
        const scene = new THREE.Scene();
        scene.background = new THREE.Color( 0xbfe3dd );
		scene.environment = pmremGenerator.fromScene( new RoomEnvironment( renderer ), 0.04 ).texture;


        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );

        
        container.appendChild(stats.domElement);
        container.appendChild(renderer.domElement);


        const controls = new OrbitControls( camera, renderer.domElement );
        controls.target.set( 0, 0.5, 0 );
        controls.update();
        controls.enablePan = true;
        controls.enableDamping = true;

        // 解压
        const dracoLoader = new DRACOLoader();
		dracoLoader.setDecoderPath( '/public/js/' );

        const loader = new GLTFLoader();
		loader.setDRACOLoader( dracoLoader );


        loader.load( '/public/modals/LittlestTokyo.glb', function ( gltf ) {

            const model = gltf.scene;
            model.position.set( 1, 1, 0 );
            model.scale.set( 0.01, 0.01, 0.01 );
            scene.add( model );

            mixer = new THREE.AnimationMixer( model );
            mixer.clipAction( gltf.animations[ 0 ] ).play();

            animate();

        }, undefined, function ( e ) {

            console.error( e );

        } );

        function animate() {

            requestAnimationFrame( animate );

            const delta = clock.getDelta();

            mixer.update( delta );

            controls.update();

            stats.update();

            renderer.render( scene, camera );

        }

    }, [])

    return (<div ref={wraperRef}></div>)

}

export default ThreeComponent;